import Dep, { pushTarget, popTarget } from './dep';

export default class Watcher {
  constructor(getter, options = {}) {
    // 在本栗子中，getter 数据更新到视图层的函数
    const { computed, watch, watchCallback } = options;
    this.getter = getter;
    this.computed = computed;
    this.watch = watch;
    this.watchCallback = watchCallback;
    this.value = undefined;
    if (this.computed) {
      // 如果是 computed
      // 则重新定一个一个依赖收集器，收集这个计算属性依赖的响应式数据
      // 此时 getter 是渲染函数，dep 是依赖集合(一堆watcher实例)
      this.dep = new Dep();
    } else {
      this.get();
    }
  }

  get() {
    // watcher 就是在特定时机触发的一个函数
    pushTarget(this);
    this.value = this.getter();
    popTarget();
    return this.value;
  }

  depend() {
    this.dep.depend();
  }

  update() {
    this.get();
    if (this.computed) {
      this.dep.notify();
    } else if (this.watch) {
      const oldValue = this.value;
      // this.get();
      this.watchCallback(this.value, oldValue);
    }
  }
}
